import cv2
import matplotlib.pyplot as plt
import numpy as np
from holoviews.core.traversal import hierarchical
from numba import uint8
from sympy.abc import epsilon


def cv_show(name,img):
    cv2.imshow(name,img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

img = cv2.imread('C:/Users/nic/Desktop/opencv/picture/duo.jpg')

#先把图像转化为灰度图
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#再把灰度图转换为二值图
ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)
#contours是轮廓信息，hierarchy是结构层次
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
#contours保存所有的轮廓信息，但不能一次计算所有的轮廓，要选择一条轮廓进行计算
cnt = contours[4]
#计算轮廓的面积
print(cv2.contourArea(cnt))
#如果是True则计算该闭合轮廓的周长
print(cv2.arcLength(cnt,True))
#轮廓近似
epsilon = 0.07 * cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
#绘制轮廓
img_same = img.copy()
res = cv2.drawContours(img_same,[approx],-1,(0,0,255),5)
#一起展示
res = np.hstack((res,img))
cv_show('all',res)
